package com.etooling.framework.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author X
 * @title: PdfToImg
 * @projectName ems
 * @description: pdf转img
 * @date 2021/11/2211:02
 */
public class PdfToImgUtil {
    private List<byte[]> pdf2images(File pdfFile) throws Exception {
        //加载PDF
        PDDocument pdDocument = PDDocument.load(pdfFile);
        //创建PDF渲染器
        PDFRenderer renderer = new PDFRenderer(pdDocument);
        int pages = pdDocument.getNumberOfPages();
        List<byte[]> images = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            //将PDF的每一页渲染成一张图片
            BufferedImage image = renderer.renderImage(i,1f);
            ImageIO.write(image, "png", output);
            images.add(output.toByteArray());
        }
        pdDocument.close();
        return images;
    }


    private List<byte[]> pdfToImgByRequest(File pdfFile) throws Exception {
        //加载PDF
        PDDocument pdDocument = PDDocument.load(pdfFile);
        //创建PDF渲染器
        PDFRenderer renderer = new PDFRenderer(pdDocument);
        int pages = pdDocument.getNumberOfPages();
        List<byte[]> images = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            //将PDF的每一页渲染成一张图片
            BufferedImage image = renderer.renderImage(i,1f);
            ImageIO.write(image, "png", output);
            images.add(output.toByteArray());
        }
        pdDocument.close();
        return images;
    }


    public static void main(String[] args) throws Exception {
        long starTime=System.currentTimeMillis();

        PdfToImgUtil pti = new PdfToImgUtil();
        List<byte[]> images = pti.pdf2images(new File("C:/Users/X/Desktop/近期/testPdf/NSP-04-101-IR2126 摆臂.pdf"));
        AtomicInteger fileNameIndex = new AtomicInteger(1);
        for (byte[] image : images) {
            new ByteArrayInputStream(image).transferTo(
                    new FileOutputStream("C:/Users/X/Desktop/近期/testPdf/" + fileNameIndex.getAndIncrement() + ".png"));
        }
        long endTime=System.currentTimeMillis();
        long Time=endTime-starTime;
        System.out.println(Time+"ms");
    }
}
